package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.YnStatusEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AppCreateJobBill;
import com.ruoyi.system.domain.JobPersonnelV2;
import com.ruoyi.system.domain.JobPlanBillDeclare;
import com.ruoyi.system.domain.JobSpecialConfig;
import com.ruoyi.system.entity.AppNextCreateConfig;
import com.ruoyi.system.entity.JobNextConfig;
import com.ruoyi.system.mapper.AppNextCreateConfigMapper;
import com.ruoyi.system.mapper.JobNextConfigMapper;
import com.ruoyi.system.mapper.JobPlanBillDeclareMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.request.AppNextStepRequest;
import com.ruoyi.system.response.AppNextStepResponse;
import com.ruoyi.system.service.AppCreateJobBillService;
import com.ruoyi.system.service.AppNextStepService;
import com.ruoyi.system.service.JobSpecialConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AppNextStepServiceImpl implements AppNextStepService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private JobNextConfigMapper jobNextConfigMapper;
    @Resource
    private AppNextCreateConfigMapper appNextCreateConfigMapper;

    @Resource
    private JobSpecialConfigService jobSpecialConfigService;

    @Autowired
    private AppCreateJobBillService appCreateJobBillService;
    @Autowired
    private JobPlanBillDeclareMapper jobPlanBillDeclareMapper;

    @Override
    public AjaxResult nextStep(AppNextStepRequest appNextStepRequest) {
        AppCreateJobBill appCreateJobBill = appCreateJobBillService.queryById(appNextStepRequest.getId());
        log.info("app 操作签字审批 流程 参数:{} 结果:{}", JSON.toJSONString(appNextStepRequest), JSON.toJSONString(appCreateJobBill));
        if (null == appCreateJobBill) {
            return AjaxResult.success("未查询到对应的作业票");
        }
        //检查是否为动火作业票
        if (!"2".equals(appCreateJobBill.getJobType())) {
            return AjaxResult.success("非动火作业票,流程未配置。");
        } else {
            saveDhCreateConfig(appNextStepRequest, appCreateJobBill);
        }
        //检查作业票是否为空
        String content = appCreateJobBill.getContent();
        if (StringUtils.isEmpty(content)) {
            return AjaxResult.success("作业票详情未配置。");
        }
        Map<String, Object> map = JSONObject.parseObject(content);
        if (map.isEmpty()) {
            return AjaxResult.success("作业票详情未配置。");
        }

        //根据作业票查询配置
        JobSpecialConfig jobSpecialConfig = new JobSpecialConfig();

        //TODO 使用多条件判断语法处理

        if ("2".equals(appCreateJobBill.getJobType())) {
            jobSpecialConfig.setJobType("二级动火作业");
        }

        List<JobSpecialConfig> specialConfigs = jobSpecialConfigService.queryAll(jobSpecialConfig);
        if (CollectionUtils.isEmpty(specialConfigs)) {
            return AjaxResult.success("作业票审批流程未配置");
        }

        Map<String, AppNextCreateConfig> finalMap = new HashMap<>();
        AppNextCreateConfig appNextCreateConfig = new AppNextCreateConfig();
        appNextCreateConfig.setVid(appNextStepRequest.getId());
        List<AppNextCreateConfig> appNextCreateConfigs = appNextCreateConfigMapper.queryAll(appNextCreateConfig);
        if (!CollectionUtils.isEmpty(appNextCreateConfigs)) {
            finalMap = appNextCreateConfigs.stream().collect(Collectors.toMap(AppNextCreateConfig::getName, el -> el, (e1, e2) -> e1));
        }

        AppNextStepResponse appNextStepResponse = new AppNextStepResponse();
        List<JobNextConfig> jobNextConfigs = jobNextConfigMapper.queryAll(new JobNextConfig());
        if (!CollectionUtils.isEmpty(jobNextConfigs)) {
            for (JobNextConfig jobNextConfig : jobNextConfigs) {

                //如果根据id匹配到,可以直接返回负责人
                Object key = map.get(jobNextConfig.getMapKey());
                if (null == key || StringUtils.isEmpty(key.toString())) {

                    //判断是否特殊处理
                    if (YnStatusEnum.N.getCode().equals(jobNextConfig.getYn())) {
                        AppNextCreateConfig nextCreateConfig = finalMap.get(jobNextConfig.getName());
                        appNextStepResponse.setStep(jobNextConfig.getStep());
                        appNextStepResponse.setPoint(jobNextConfig.getMapKey());
                        appNextStepResponse.setHandById(nextCreateConfig.getContentId());
                        appNextStepResponse.setHandBy(nextCreateConfig.getContent());
                        return AjaxResult.success(appNextStepResponse);
                    }

                    JobSpecialConfig specialConfig = specialConfigs.stream().filter(val -> jobNextConfig.getName().equals(val.getLinkName())).findFirst().orElse(null);
                    if (null == specialConfig) {
                        return AjaxResult.success(jobNextConfig.getValue());
                    }
                    appNextStepResponse.setStep(jobNextConfig.getStep());
                    appNextStepResponse.setPoint(jobNextConfig.getMapKey());
                    appNextStepResponse.setHandById(specialConfig.getHandById());
                    appNextStepResponse.setHandBy(specialConfig.getHandBy());
                    return AjaxResult.success(appNextStepResponse);
                }
            }
        }

        //流程操作判断
        return AjaxResult.success();
    }

    private void saveDhCreateConfig(AppNextStepRequest appNextStepRequest, AppCreateJobBill appCreateJobBill) {
        //需要根据id先把配置表删除
        appNextCreateConfigMapper.deleteById(appNextStepRequest.getId());

        JobPlanBillDeclare jobPlanBillDeclare = new JobPlanBillDeclare();
        jobPlanBillDeclare.setBillNumber(appCreateJobBill.getPtw());
        List<JobPlanBillDeclare> jobPlanBillDeclares = jobPlanBillDeclareMapper.queryAll(jobPlanBillDeclare);
        JobPlanBillDeclare planBillDeclare = jobPlanBillDeclares.stream().findFirst().orElse(null);
        log.info("作业票结果:{}", JSON.toJSONString(planBillDeclare));
        if (null == planBillDeclare) {
            log.error("planBillDeclare 信息为空！");
            return;
        }

        String jobPersonnel = planBillDeclare.getJobPersonnel();
        if (StringUtils.isEmpty(jobPersonnel)) {
            log.error("jobPersonnel 信息为空！");
            return;
        }

        List<JobPersonnelV2> personnelV2s = JSON.parseArray(jobPersonnel, JobPersonnelV2.class);
        Map<Integer, JobPersonnelV2> jobPersonnelV2Map = personnelV2s.stream().collect(Collectors.toMap(JobPersonnelV2::getId, el -> el, (e1, e2) -> e1));
        JobPersonnelV2 jobPersonnelV2 = jobPersonnelV2Map.get(Integer.valueOf(planBillDeclare.getJobPersonChargeId()));
        JobPersonnelV2 jobPersonnelV3 = jobPersonnelV2Map.get(Integer.valueOf(planBillDeclare.getCustodyId()));

        List<AppNextCreateConfig> appNextCreateConfigs = new ArrayList<>();

        String jobPersonChargeId = "";
        String jobPersonCharge = "";
        String custodyId = "";
        String custodyName = "";

        //作业负责人意见
        AppNextCreateConfig appNextCreateConfigOne = new AppNextCreateConfig();
        appNextCreateConfigOne.setVid(appNextStepRequest.getId());
        appNextCreateConfigOne.setName("作业负责人意见");
        if ("in".equals(jobPersonnelV2.getType())) {
            jobPersonChargeId = planBillDeclare.getJobPersonChargeId();
            jobPersonCharge = planBillDeclare.getJobPersonCharge();
            appNextCreateConfigOne.setContentId(planBillDeclare.getJobPersonChargeId());
            appNextCreateConfigOne.setContent(planBillDeclare.getJobPersonCharge());
        } else {
            SysUser vidInfo = sysUserMapper.getVidInfo(Long.valueOf(planBillDeclare.getJobPersonChargeId()));
            jobPersonChargeId = vidInfo.getUserId().toString();
            jobPersonCharge = vidInfo.getUserName();
            appNextCreateConfigOne.setContentId(vidInfo.getUserId().toString());
            appNextCreateConfigOne.setContent(vidInfo.getUserName());
        }
        appNextCreateConfigs.add(appNextCreateConfigOne);

        //安全措施确认
        AppNextCreateConfig appNextCreateConfigTwo = new AppNextCreateConfig();
        appNextCreateConfigTwo.setVid(appNextStepRequest.getId());
        appNextCreateConfigTwo.setName("安全措施确认");
        if ("in".equals(jobPersonnelV3.getType())) {
            custodyId = planBillDeclare.getCustodyId();
            custodyName = planBillDeclare.getCustody();
            appNextCreateConfigTwo.setContentId(planBillDeclare.getCustodyId());
            appNextCreateConfigTwo.setContent(planBillDeclare.getCustody());
        } else {
            SysUser vidInfo = sysUserMapper.getVidInfo(Long.valueOf(planBillDeclare.getCustodyId()));
            custodyId = vidInfo.getUserId().toString();
            custodyName = vidInfo.getUserName();
            appNextCreateConfigTwo.setContentId(vidInfo.getUserId().toString());
            appNextCreateConfigTwo.setContent(vidInfo.getUserName());
        }
        appNextCreateConfigs.add(appNextCreateConfigTwo);

        //监护人
        AppNextCreateConfig appNextCreateConfigThree = new AppNextCreateConfig();
        appNextCreateConfigThree.setVid(appNextStepRequest.getId());
        appNextCreateConfigThree.setName("监护人");
        appNextCreateConfigThree.setContentId(custodyId);
        appNextCreateConfigThree.setContent(custodyName);
        appNextCreateConfigs.add(appNextCreateConfigThree);

        //实际动火时间
        AppNextCreateConfig appNextCreateConfigFour = new AppNextCreateConfig();
        appNextCreateConfigFour.setVid(appNextStepRequest.getId());
        appNextCreateConfigFour.setName("实际动火时间");
        appNextCreateConfigFour.setContentId(custodyId);
        appNextCreateConfigFour.setContent(custodyName);
        appNextCreateConfigs.add(appNextCreateConfigFour);

        //完成验收
        AppNextCreateConfig appNextCreateConfigFive = new AppNextCreateConfig();
        appNextCreateConfigFive.setVid(appNextStepRequest.getId());
        appNextCreateConfigFive.setName("完成验收");
        appNextCreateConfigFive.setContentId(custodyId);
        appNextCreateConfigFive.setContent(custodyName);
        appNextCreateConfigs.add(appNextCreateConfigFive);

        appNextCreateConfigMapper.insertBatch(appNextCreateConfigs);
    }

}
